//
//  VVComposeView.swift
//  Weibo
//
//  Created by 王惠平 on 2017/4/4.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit
import pop
import YYModel

class VVComposeView: UIView {
    
    //懒加载图片
    //背景模糊图片
    fileprivate lazy var bgImageView: UIImageView = {
        
        let imageView = UIImageView()
    
        //设置截屏图片,把图片模糊化
        imageView.image = self.getScreenShot().applyLightEffect()

        return imageView
        
    }()
    
    //标语
    fileprivate lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    //目标控制器
    var target: UIViewController?
    
    //compose数组
    lazy var composeArray: [VVCompose] = {
        
       return self.getPlistData()
        
    }()
    
    //保存6个撰写菜单按钮
    fileprivate lazy var composeButtonArray: [VVComposeButton] = [VVComposeButton]()

    override init(frame: CGRect) {
    
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
    //设置当前视图的大小
    size = CGSize(width: ScreenWidth, height: ScreenHeight)
    
    //backgroundColor = RandomColor()
        
        addSubview(bgImageView)
        addSubview(sloganImageView)
        
        bgImageView.snp.makeConstraints { (make) in
            
            make.edges.equalTo(self)
        }
        
        sloganImageView.snp.makeConstraints { (make) in
            
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(150)
        }
        
        addChildButton()
        
        popAnimation(isUp: true)
    }
    
    fileprivate func addChildButton() {
        
//        let button = VVComposeButton()
//        
//        button.setImage(UIImage(named:"tabbar_compose_idea"), for: .normal)
//        
//        button.setTitle("文字", for: .normal)
//        
//        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        
//        button.setTitleColor(UIColor.darkGray, for: .normal)
//        
//        button.size = CGSize(width: 80, height: 110)
//        
//        addSubview(button)
        
        //按钮的大小
        let buttonWidth: CGFloat = 80
        let buttonHeight: CGFloat = 110
        
        //按钮之间的间距
        let buttonMargin: CGFloat = (width - 3 * buttonWidth) / 4
        
        for i in 0..<composeArray.count {
            
            let button = VVComposeButton()
            
            //通过点击按钮的tag获取对应的模型
            button.tag = i
            
            button.addTarget(self, action: #selector(composeButtonAction(btn:)), for: .touchUpInside)
           
//            button.setImage(UIImage(named:"tabbar_compose_idea"), for: .normal)
//            
//            button.setTitle("文字", for: .normal)
            
            //根据下标获取模型
            let compose = composeArray[i]
            
            button.setImage(UIImage(named:compose.icon!), for: .normal)
            
            button.setTitle(compose.title!, for: .normal)
            
            button.setTitleColor(UIColor.darkGray, for: .normal)
            
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            
            //计算列的索引
            let colIndex = i % 3
            
            //计算行的索引
            let rowIndex = i / 3
            
            //设置x坐标
            button.x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonMargin
            
            //设置y坐标
            button.y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * buttonMargin + ScreenHeight
            
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            
            addSubview(button)
            
            //保存到数组中
            composeButtonArray.append(button)
        }
     
    }
    
   @objc private func composeButtonAction(btn: VVComposeButton) {
    
    //通过tag获取模型
   let compose = composeArray[btn.tag]
    
    UIView.animate(withDuration: 0.25, animations: {
        
        for button in self.composeButtonArray {
            
            button.alpha = 0.3
            
            if button == btn {
                
                //放大
                button.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
                
            } else {
                
                //缩小
                button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
            }
            
        }
        
    }) { (_) in
        
        UIView.animate(withDuration: 0.25, animations: {
            
            for button in self.composeButtonArray {
                
                button.alpha = 1
                
                //重置
                button.transform = CGAffineTransform.identity
            }
            
        }, completion: { (_) in
            
            //弹出视图控制器
//            let className = NSStringFromClass(VVComposeViewController.self)
//            print(className)
            
            //弹出控制器
            //通过类名字符串转成class类型-> 在swift里面自定义的类如果想要通过类名字符串转class,需要加命名空间
            let classType = NSClassFromString(compose.className!) as! UIViewController.Type
            
            //通过class类型获取实例->把anycLASS转成对应的class类型(as? UIViewController.Type)不能用(),改成.init()
            let vc = classType.init()
            
            //print(vc)
            
            //创建导航控制器
            let nav = VVNavigationViewController(rootViewController: vc)
            
            //再次需要视图控制器
            self.target?.present(nav, animated: true, completion: {
                
                //移除罩层
                self.removeFromSuperview()
            })
        })
    }
  
    }
    
    //pop动画
    fileprivate func popAnimation(isUp: Bool) {
        
        //如果是向下的动画,数组翻转
        if isUp == false {
            
            composeButtonArray = composeButtonArray.reversed()
        }
    
    //遍历pop动画
        for (i, button) in composeButtonArray.enumerated() {
        
            //创建pop动画
            let pop = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            
            //抖动幅度
            pop?.springBounciness = 10
            
            //弹簧速度
            pop?.springSpeed = 10
            
            //动画开始时间的间隔
            pop?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            
            if isUp {
                //动画执行的目的地
                pop?.toValue = CGPoint(x: button.centerX, y: button.centerY - 350)
            } else {
                
                //动画执行的目的地
                pop?.toValue = CGPoint(x: button.centerX, y: button.centerY + 350)
            }
          
            button.pop_add(pop, forKey: nil)
        }
    
    }
    //截屏操作
    fileprivate func getScreenShot() ->UIImage {
        
        //获取window
        let window = UIApplication.shared.keyWindow!
        
        //开启图片上下文
        UIGraphicsBeginImageContext(window.size)
        
        //完成的是截屏的操作
        window.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: window.size), afterScreenUpdates: false)
        
        //从当前上下文中获取图片
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        
        //关闭图片上下文
        UIGraphicsEndImageContext()
        
        return currentImage!
        
    }
    
    //显示罩层
    func show(target: UIViewController) {
        
        //保存目标控制器
        self.target = target
        
        //把视图添加到tabbarController上
        self.target?.view.addSubview(self)
        
    }
    
    //获取plist文件数据
    fileprivate func getPlistData() ->[VVCompose] {
        
        //获取plist文件路径
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        
        //读取plist文件数据
        let dicArray = NSArray(contentsOfFile: path) as! [[String: Any]]
        
        //使用YYModel转成数组模型
        let modelArray = NSArray.yy_modelArray(with: VVCompose.self, json: dicArray) as! [VVCompose]
        
        return modelArray
    
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        //执行向下的动画
        popAnimation(isUp: false)
        
        //gcd延时
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            
            self.removeFromSuperview()
        }
    }

}
